import Vue from "vue";
import VueRouter from "vue-router";
import store from "@/store";
import axios from "axios";

Vue.use(VueRouter);

const router = new VueRouter({
  mode: 'history',
  routes: [
    {
      path: "/login",
      name: "AdminLogin",
      component: () => import("@/views/login"),
    },
    {
      path: "/",
      name: "Home",
      redirect: "/admin",
    },
    {
      path: "/admin",
      name: "AdminHome",
      component: () => import("@/views/home"),
    },
    {
      path: "/404",
      name: "NotFound",
      component: () => import("@/views/404"),
    },
    {
      path: "*",
      redirect: "/404",
    },
  ],
});

router.beforeEach((to, from, next) => {
  if (to.path.startsWith("/admin") && !store.state.auth) {
    axios.post("/api/admin/verify")
      .then(res => {
        const code = res.data.statusCode;
        if (code === 200) {
          store.commit("auth");
          next();
        } else {
          next({name: "AdminLogin", query: {redirect: from.fullPath,}});
        }
      });
  } else {
    next();
  }
})

export default router;